import React, { useState, useEffect } from 'react';
import { ArrowLeft, Save, RotateCcw, Plus, Trash2 } from 'lucide-react';
import { useAppStore } from '../stores/appStore';
import { ShortcutConfig } from '../types';
import { safeTauriInvoke } from '../utils/tauriHelper';

const SettingsPage: React.FC = () => {
  const { 
    setCurrentMode, 
    opacity, 
    alwaysOnTop, 
    opacityPresets, 
    setOpacityPresets,
    shortcuts,
    setShortcuts
  } = useAppStore();

  const [localShortcuts, setLocalShortcuts] = useState<ShortcutConfig>(shortcuts);
  const [localPresets, setLocalPresets] = useState<number[]>(opacityPresets);
  const [newPreset, setNewPreset] = useState<string>('');
  const [autoHide, setAutoHide] = useState(false);
  const [startupPosition, setStartupPosition] = useState({ x: 100, y: 100 });
  const [startupSize, setStartupSize] = useState({ width: 1200, height: 800 });

  // 保存设置
  const handleSaveSettings = async () => {
    try {
      const config = {
        window: {
          opacity: opacity,
          alwaysOnTop: alwaysOnTop,
          width: 1200,
          height: 800
        },
        shortcuts: localShortcuts,
        behavior: {
          hideOnStartup: false,
          minimizeToTray: true,
          autoHideDelay: 0
        }
      };
      
      await safeTauriInvoke('save_config', { config });
      
      // 保存快捷键设置
      setShortcuts(localShortcuts);
      
      // 保存透明度预设
      setOpacityPresets(localPresets);
      
      // 显示保存成功提示
      alert('设置保存成功！');
    } catch (error) {
      console.error('保存设置失败:', error);
      alert('保存设置失败！');
    }
  };

  // 重置设置
  const handleResetSettings = () => {
    const defaultShortcuts: ShortcutConfig = {
      toggleVisibility: 'Ctrl+Shift+H',
      increaseOpacity: 'Ctrl+Shift+Up',
      decreaseOpacity: 'Ctrl+Shift+Down',
      toggleDisguise: 'Ctrl+Shift+D'
    };
    
    const defaultPresets = [0.3, 0.5, 0.7, 0.9, 1.0];
    
    setLocalShortcuts(defaultShortcuts);
    setLocalPresets(defaultPresets);
    setAutoHide(false);
    setStartupPosition({ x: 100, y: 100 });
    setStartupSize({ width: 1200, height: 800 });
  };

  // 添加透明度预设
  const handleAddPreset = () => {
    const value = parseFloat(newPreset);
    if (value >= 0.1 && value <= 1.0 && !localPresets.includes(value)) {
      setLocalPresets([...localPresets, value].sort());
      setNewPreset('');
    }
  };

  // 删除透明度预设
  const handleRemovePreset = (preset: number) => {
    setLocalPresets(localPresets.filter(p => p !== preset));
  };

  // 更新快捷键
  const handleShortcutChange = (key: keyof ShortcutConfig, value: string) => {
    setLocalShortcuts({
      ...localShortcuts,
      [key]: value
    });
  };

  // const handleRegisterShortcut = async (action: string, shortcut: string) => {
  //   try {
  //     const invoke = await getInvoke();
  //     await invoke('register_global_shortcut', { action, shortcut });
  //     console.log(`快捷键 ${shortcut} 注册成功`);
  //   } catch (error) {
  //     console.error('注册快捷键失败:', error);
  //   }
  // };

  // 加载配置
  const loadConfig = async () => {
    try {
      const config = await safeTauriInvoke('load_config') as any;
      
      if (config) {
        setLocalShortcuts(config.shortcuts || {
          toggleVisibility: 'Ctrl+Shift+H',
          increaseOpacity: 'Ctrl+Shift+Up',
          decreaseOpacity: 'Ctrl+Shift+Down',
          toggleDisguise: 'Ctrl+Shift+D'
        });
      }
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  };

  // 组件挂载时加载配置
  useEffect(() => {
    loadConfig();
  }, []);

  return (
    <div className="w-full h-screen bg-gray-900 text-white overflow-auto">
      {/* 顶部导航 */}
      <div className="bg-gray-800 border-b border-gray-700 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => setCurrentMode('reading')}
              className="flex items-center space-x-2 text-gray-300 hover:text-white transition-colors"
            >
              <ArrowLeft size={20} />
              <span>返回主界面</span>
            </button>
          </div>
          <h1 className="text-xl font-semibold">应用设置</h1>
          <div className="flex items-center space-x-2">
            <button
              onClick={handleResetSettings}
              className="flex items-center space-x-1 px-3 py-2 bg-gray-600 hover:bg-gray-500 rounded transition-colors"
            >
              <RotateCcw size={16} />
              <span>重置</span>
            </button>
            <button
              onClick={handleSaveSettings}
              className="flex items-center space-x-1 px-3 py-2 bg-blue-600 hover:bg-blue-500 rounded transition-colors"
            >
              <Save size={16} />
              <span>保存</span>
            </button>
          </div>
        </div>
      </div>

      <div className="p-6 space-y-8">
        {/* 透明度预设设置 */}
        <div className="bg-gray-800 rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">透明度预设</h2>
          
          {/* 当前预设列表 */}
          <div className="mb-4">
            <div className="grid grid-cols-6 gap-2 mb-4">
              {localPresets.map((preset) => (
                <div key={preset} className="flex items-center space-x-2 bg-gray-700 rounded p-2">
                  <span className="flex-1 text-sm">{Math.round(preset * 100)}%</span>
                  <button
                    onClick={() => handleRemovePreset(preset)}
                    className="text-red-400 hover:text-red-300 transition-colors"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              ))}
            </div>
            
            {/* 添加新预设 */}
            <div className="flex items-center space-x-2">
              <input
                type="number"
                min="0.1"
                max="1"
                step="0.05"
                value={newPreset}
                onChange={(e) => setNewPreset(e.target.value)}
                placeholder="0.8"
                className="px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white placeholder-gray-400 focus:border-blue-500 focus:outline-none"
              />
              <button
                onClick={handleAddPreset}
                className="flex items-center space-x-1 px-3 py-2 bg-green-600 hover:bg-green-500 rounded transition-colors"
              >
                <Plus size={16} />
                <span>添加</span>
              </button>
            </div>
          </div>
        </div>

        {/* 快捷键设置 */}
        <div className="bg-gray-800 rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">快捷键配置</h2>
          
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium mb-2">切换窗口显示/隐藏</label>
                <input
                  type="text"
                  value={localShortcuts.toggleVisibility}
                  onChange={(e) => handleShortcutChange('toggleVisibility', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">增加透明度</label>
                <input
                  type="text"
                  value={localShortcuts.increaseOpacity}
                  onChange={(e) => handleShortcutChange('increaseOpacity', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">减少透明度</label>
                <input
                  type="text"
                  value={localShortcuts.decreaseOpacity}
                  onChange={(e) => handleShortcutChange('decreaseOpacity', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">切换伪装模式</label>
                <input
                  type="text"
                  value={localShortcuts.toggleDisguise}
                  onChange={(e) => handleShortcutChange('toggleDisguise', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
            </div>
          </div>
        </div>

        {/* 窗口行为设置 */}
        <div className="bg-gray-800 rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">窗口行为</h2>
          
          <div className="space-y-4">
            {/* 自动隐藏 */}
            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">失去焦点时自动隐藏</div>
                <div className="text-sm text-gray-400">当窗口失去焦点时自动隐藏窗口</div>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={autoHide}
                  onChange={(e) => setAutoHide(e.target.checked)}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>
            
            {/* 启动位置 */}
            <div>
              <label className="block text-sm font-medium mb-2">启动位置</label>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <input
                    type="number"
                    value={startupPosition.x}
                    onChange={(e) => setStartupPosition({...startupPosition, x: parseInt(e.target.value)})}
                    placeholder="X坐标"
                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
                <div>
                  <input
                    type="number"
                    value={startupPosition.y}
                    onChange={(e) => setStartupPosition({...startupPosition, y: parseInt(e.target.value)})}
                    placeholder="Y坐标"
                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
              </div>
            </div>
            
            {/* 启动大小 */}
            <div>
              <label className="block text-sm font-medium mb-2">启动大小</label>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <input
                    type="number"
                    value={startupSize.width}
                    onChange={(e) => setStartupSize({...startupSize, width: parseInt(e.target.value)})}
                    placeholder="宽度"
                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
                <div>
                  <input
                    type="number"
                    value={startupSize.height}
                    onChange={(e) => setStartupSize({...startupSize, height: parseInt(e.target.value)})}
                    placeholder="高度"
                    className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 当前状态信息 */}
        <div className="bg-gray-800 rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">当前状态</h2>
          
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-gray-400">当前透明度:</span>
              <span className="ml-2 text-blue-400">{Math.round(opacity * 100)}%</span>
            </div>
            <div>
              <span className="text-gray-400">窗口置顶:</span>
              <span className={`ml-2 ${alwaysOnTop ? 'text-green-400' : 'text-red-400'}`}>
                {alwaysOnTop ? '已启用' : '已禁用'}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingsPage;